/**
 * 对100万条long数据进行升序排序，几种简单排序之间的比较。
 * 2018年 03月 22日 星期四
 *
 * @author fireway
 */
import java.util.Iterator;

public class LongArray implements Iterable<Long> {
    private long mLArray[];

    private int mSize;

    public LongArray(int initialCapacity) {
        mLArray = new long[initialCapacity];
        mSize = 0;
    }

    public void insert(long value) {
        mLArray[mSize++] = value;
    }

    public void display() {
        System.out.print("[");
        for (int i = 0; i < mSize; i++) {
            System.out.print(mLArray[i]);
            if (i != mSize -1) {
                System.out.print(", ");
            }
        }
        System.out.print("]\n");
    }

    public int size() {
        return mSize;
    }

    public void bubbleSort() {
        for (int i = mSize - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (mLArray[j] > mLArray[j + 1]) {
                    long temp = mLArray[j + 1];
                    mLArray[j + 1] = mLArray[j];
                    mLArray[j] = temp;
                }
            }
        }
    }

    public void selectSort() {
        for (int i = 0; i < mSize - 1; i++) {
            int min = i;
            for (int j = i + 1; j < mSize; j++) {
                if (mLArray[j] < mLArray[min]) {
                    min = j;
                }
            }

            long tmp = mLArray[i];
            mLArray[i] = mLArray[min];
            mLArray[min] = tmp;
        }
    }

    public void insertSort() {
        for (int i = 1; i < mSize; i++) {
            long tmp = mLArray[i];
            int j = i;
            while (j > 0 && mLArray[j - 1] >= tmp) {
                mLArray[j] = mLArray[j - 1];
                j--;
            }

            mLArray[j] = tmp;
        }
    }

    public Long remove(int index) {
        Long result = mLArray[index];
        for (int i = index; i < mSize - 1; i++) {
            mLArray[i] = mLArray[i + 1];
        }
        mSize--;
        return result;
    }

    @Override
    public Iterator<Long> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<Long> {
        int cursor = 0;

        int lastRet = mSize - 1;

        @Override
        public boolean hasNext() {
            return cursor != size();
        }

        @Override
        public Long next() {
            Long next = mLArray[cursor];
            cursor++;
            return next;
        }

        @Override
        public void remove() {
            LongArray.this.remove(lastRet);
        }
    }
}
